from django.shortcuts import render
from drf_haystack.viewsets import HaystackViewSet
from rest_framework import filters
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.response import Response

from apps.goods.models import SKU

#热销商品
from apps.goods.serializers import HotSkuListSerializer, SKUIndexSerializer


#热门商品类视图
class HotSkuListView(ListAPIView):
    serializer_class = HotSkuListSerializer

    #这个取消分页
    pagination_class = None

    #重写方法，为了能用三级视图
    def get_queryset(self):
        #获取路由地址中的资源参数
        category_id=self.kwargs.get("category_id")
        #根据类别id查出热销商品的前3个
        skus=SKU.objects.filter(category_id=category_id).order_by("-sales")[:3]
        return skus

    # def get(self,request,category_id):
    #     query=self.get_queryset()
    #     serializer=self.get_serializer(instance=query,many=True)
    #     return Response(serializer.data)

#商品列表
class SkuListView(ListAPIView):

    serializer_class = HotSkuListSerializer

    #设置过滤后端,排序字段
    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('create_time', 'price',"sales")

    def get_queryset(self):
        #1,获取分类编号
        category_id = self.kwargs.get("category_id")

        #2,根据分类编号查询数据
        skus = SKU.objects.filter(category_id=category_id)

        return skus

#haystack搜索类视图
class  SKUSearchViewSet(HaystackViewSet):
    #指定视图集
    index_models = [SKU]
    #指定序列化器
    serializer_class = SKUIndexSerializer